package com.thghh.bcode.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

/**
 * @author Zhikang.Peng
 * @version 1.0
 * @email thghh@qq.com
 * @date 2020/12/15 16:12
 */
public class ByteArrayAppendable extends ByteArrayOutputStream implements Appendable {

    private ByteArrayOutputStream output;

    public ByteArrayAppendable() {
        this(new ByteArrayOutputStream(2048));
    }

    public ByteArrayAppendable(ByteArrayOutputStream output) {
        this.output = output;
    }

    @Override
    public Appendable append(CharSequence csq) throws IOException {
        Objects.requireNonNull(csq);
        String s = csq.toString();
        write(s, 0, s.length());
        return this;
    }

    @Override
    public Appendable append(CharSequence csq, int start, int end) throws IOException {
        Objects.requireNonNull(csq);
        String s = csq.subSequence(start, end).toString();
        write(s, 0, s.length());
        return this;
    }

    @Override
    public Appendable append(char c) throws IOException {
        output.write(c);
        return this;
    }

    /**
     * Write a portion of a string to the buffer.
     *
     * @param str String to be written from
     * @param off Offset from which to start reading characters
     * @param len Number of characters to be written
     */
    public void write(String str, int off, int len) {
        byte[] b = str.getBytes();
        output.write(b, off, len);
    }

    @Override
    public synchronized void write(int b) {
        output.write(b);
    }

    @Override
    public synchronized void write(byte[] b, int off, int len) {
        output.write(b, off, len);
    }

    @Override
    public synchronized void writeTo(OutputStream out) throws IOException {
        output.writeTo(out);
    }

    @Override
    public synchronized void reset() {
        output.reset();
    }

    @Override
    public synchronized byte[] toByteArray() {
        return output.toByteArray();
    }

    @Override
    public synchronized int size() {
        return output.size();
    }

    @Override
    public synchronized String toString() {
        return output.toString();
    }

    @Override
    public synchronized String toString(String charsetName) throws UnsupportedEncodingException {
        return output.toString(charsetName);
    }

    @Override
    public synchronized String toString(int hibyte) {
        return output.toString(hibyte);
    }

    @Override
    public void close() throws IOException {
        output.close();
    }
}
